package pers.w.chaptertalk.funs;


import android.os.Handler;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ContentThread extends Thread implements Runnable, IReader {

    private static final String TAG = "content task";
    private Handler handler;
    private int startOrEndOrNoChange;
    private int success = 0;
    private ChapterInfo chapterInfo;
    private List<Map<String, String>> chapters;
    private File bookDir;
    private Exception exception=null;
    public void setStop() {
        this.stop = true;
    }

    private boolean stop;

    public ContentThread(Handler handler, int startOrEndOrNoChange, ChapterInfo chapterInfo) {
        this.handler = handler;
        this.startOrEndOrNoChange = startOrEndOrNoChange;
        this.chapterInfo = chapterInfo;
    }

    public ContentThread(Handler handler, int startOrEndOrNoChange, File bookDir, List<Map<String, String>> chapters) {
        this.handler = handler;
        this.startOrEndOrNoChange = startOrEndOrNoChange;
        this.chapters = chapters;
        this.bookDir = bookDir;
    }

    @Override
    public void run() {
        if (chapterInfo != null) {
            getContent(chapterInfo);
        } else
            for(Map<String,String> map:chapters){
                if (stop) break;
                ChapterInfo chapter = new ChapterInfo(bookDir, map);

                if (chapter.chapterFile.exists()) continue;
                getContent(chapter);
            }
        if (handler != null && exception==null)
            handler.sendMessage(handler.obtainMessage(HANDLER_GET_CONTENT, success, startOrEndOrNoChange));
    }

    private void getContent(ChapterInfo chapter) {
        Document doc;
        // ChapterInfo chapter = chapterInfos[0];
        try {
            doc = Jsoup.connect(chapter.getUri()).timeout(5000).get();
        } catch (IOException e) {
            // e.printStackTrace();
            exception =e;
            return;
        }
        if (null != doc) {
            Element divContent = doc.getElementById("content");
            if (null != divContent) {
                String content = divContent.text();
                content = "\u3000\u3000" + content.replace(" ", ChapterInfo.TAG_STR) + ChapterInfo.TAG_STR + "（本章完）";

                chapter.setContent(content);
                chapter.save();
                success = 1;
            }
        }
    }

}
